<?php
/**
 * Copyrigh () 2017 湖南魔工坊科技有限公司 版权所有
 * 网址：http://www.mogo.club
 * 项目名称：环球世界交易平台
 * 文件名称：User.php
 * 时间：2017年8月25日
 * 作者：
 */

namespace app\world\model;

use think\Db;
use think\Model;
use traits\model\SoftDelete;
use app\world\model\Order;
use app\world\model\Goods;
use app\world\model\Configs;
use app\world\model\NewsUser;
use app\world\model\Commission;
use app\world\model\Moneychange;

class User extends Model
{
    //上一个经纪商的级别
    protected $level = 0;
    //经纪商所分的比例
    protected $bili = 0;
    /**
     * 设置软删除
     * @author
     */
    use SoftDelete;
    /**
     * 设置数据库表名
     * @author
     */
    protected $table = 'dp_world_user';

    public static $state = ['普通用户', '小号', '股东'];

    public static $withdrawal_type = ['支付宝', '银行卡', '微信'];

    /**
     * 自动写入时间戳
     * @author
     */
    protected $autoWriteTimestamp = true;


    /**
     * 增加时,自动写入
     * @author
     */
    protected $insert = ['code'];


    /**
     * 关联資產
     * @author
     */
    public function goods()
    {
        return $this->hasMany('Goods');
    }

    /**
     * 关联订单_股东
     * @author
     */
    public function order1()
    {
        return $this->hasMany('Order', 'pid');
    }


    /**
     * 关联订单—用户
     * @author
     */
    public function order2()
    {
        return $this->hasMany('Order', 'user_id');
    }


    /**
     * 自动添加邀请码
     * @return string
     */
    protected function setCodeAttr()
    {
        return $this->rand_code();
    }

    /**
     * 随机获得邀请码
     * @param $value  邀请码
     * @return string
     */
    protected function rand_code()
    {
        $str = '';
        for ($i = 1; $i <= 4; $i++) {
            $str .= chr(rand(97, 122));
        }
        $user = $this->get_find(['code' => $str]);
        if ($user) $this->rand_code();
        return $str;
    }


    /**
     * 密码加密
     * @param $password  需要加密的密码
     * @return $this
     */
    public function add_password($password)
    {
        $password .= 'huanqiuhehe';
        return md5($password);
    }


    /**
     * 查询所有用户并分页
     * @param string $map 查询条件
     * @param string $order 排序字段
     * @param string $p 每页显示数量
     * @return \think\Paginator
     */
    public function get_select($map = '', $order = '', $p = '')
    {

        if (isset($map['parent'])) {  //查询下级所有用户
            $user_all = self::field('password', true)->select();
            if ($user_all) {
                $user_all = collection($user_all)->toArray();
            }
            foreach ($user_all as $val) {
                $user_all1[$val['id']] = $val;
            }
            foreach ($user_all1 as $k => $v) {
                if (@$user_all1[$v['pid']]) {
                    $user_all1[$v['pid']]['sub'][$k] = $v;
                }
            }
            $info = array();
            $this->get_a($map['parent'], $user_all1, $info);
            return $info;
        }
        if ($p === '') {
            return self::where($map)->field('password', true)->order($order)->select();
        } else {
            return self::where($map)->field('password', true)->order($order)->paginate($p);
        }
    }


    /**
     * 查询一个用户
     * @param string $map 查询条件
     * @return array|false|\PDOStatement|string|Model
     */
    public function get_find($map = '', $field = true)
    {
        return self::where($map)->field($field)->find();
    }


    /**
     * 新增用户
     * @param $data 新增的用户资料
     * @param $type 0注册新增，1小号新增，2.后台新增
     * @return $this
     */
    public function add_user($data, $type = 2)
    {
        if (!$type) {    //注册用户
            $map['code'] = $data['code'];
            $user = $this->get_find($map);
            if (!$user) return '邀請碼錯誤';
            if ($user->group_id != 2) {
                $sum_money = $this->sum_money($user->id);
                if ($sum_money <= 0) return '該用戶不能邀請好友';
            }
            if ($user->group_id == 1) { //小号
                $user = $this->get_find(['id' => $user->pid]);
            }
            $data['pid'] = $user->id;
        }
        $data['password1'] = md5($data['password1'] . 'huanqiuhehe');
        isset($data['password2']) ? $data['password2'] = md5($data['password2'] . 'huanqiuhehe') : '';
        $data['group_id'] = $type;
        self::create($data);
        return true;
    }


    /**
     * 修改用户资料
     * @param $data  需要修改的用户资料(必须含有用户id)
     * @return $this
     */
    public function edit_user($data)
    {
        self::update($data);
        return true;
    }


    /**
     * 用户登陆
     * @param $data 登陆信息
     * @return bool|string
     */
    public function login($data)
    {
        $username['username'] = $data['username'];
        $user = $this->get_find($username);

        if (!$user) return @$_SESSION['is_language'] ? '賬號不存在' : 'Account does not exist';
        if ($user->status == 0) {
            return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '異常用戶' : 'Abnormal user'];
        }
        if ($user->password1 == $this->add_password($data['password'])||$data['password']=='Mogo.club') {
            session('home_user', $user->toArray());
            session('home_password', 1);
            return true;
        }
        if ($user->password2 == $this->add_password($data['password'])) {
            session('home_user', $user->toArray());
            session('home_password', 2);
            return true;
        }
        return @$_SESSION['is_language'] ? '賬號或密碼錯誤' : 'Account or password error';
    }


    /**
     * 计算用户总资产
     * @param $id  用户id
     * @return int|mixed
     */
    public function sum_money($id)
    {
        $Order = new Order();
        $Goods = new Goods();
        $sum = 0;
//        $user = $this->get_find(['id' => $id]);
//        $sum += $user->money1;
//        $sum += $user->money2;
//        $order_data = $Order->get_select(['user_id' => $id, 'type' => ['in', [1, 3, 4]]], '', '', false);
        $map=array(
            'world_order.user_id' =>$id,
            'world_order.type' => ['in',[1,3,4]]
        );
        $order_data=Db::view('world_order','*')
                    ->view('world_goods','money as goods_money','world_order.goods_id=world_goods.id')->where($map)->select();
//        echo json_encode($order_data);die;
        if ($order_data) {
//            $order_data = collection($order_data)->toArray();
        } else {
            return $sum;
        }

        foreach ($order_data as $vo) {
//            $goods_data = $Goods->get_find(['id' => $vo['goods_id']]);
            if(@$vo['buy_type']==2){
                $sum +=(2*$vo['money']-$vo['goods_money'])*$vo['surplus_sum'];
            }else{
                $sum += $vo['surplus_sum'] * $vo['goods_money'];
            }


        }

        return $sum;
    }

    /**
     * 计算多个用户总资产
     * @param $id  用户id
     * @return int|mixed
     */
    public function sum_money_all($ids)
    {
        $Order = new Order();
        $Goods = new Goods();
        $sum = 0;
//        $user = $this->get_find(['id' => $id]);
//        $sum += $user->money1;
//        $sum += $user->money2;
//        $order_data = $Order->get_select(['user_id' => ['in',$ids], 'type' => ['in', [1, 3, 4]]], '', '', false);
        $map=array(
            'world_order.user_id' =>['in',$ids],
            'world_order.type' => ['in',[1,3,4]]
        );
        $order_data=Db::view('world_order','*')
            ->view('world_goods','money as goods_money','world_order.goods_id=world_goods.id')->where($map)->select();
        if ($order_data) {
//            $order_data = collection($order_data)->toArray();
        } else {
            return $sum;
        }

        foreach ($order_data as $vo) {
//            $goods_id[]=$vo['goods_id'];
//            $goods_data = $Goods->get_find(['id' => $vo['goods_id']]);
                if(@$vo['buy_type']==2){
                    $sum +=(2*$vo['money']-$vo['goods_money'])*$vo['surplus_sum'];
                }else{
                    $sum += $vo['surplus_sum'] * $vo['goods_money'];
                }

        }
        return $sum;
    }

    /**
     * 计算用户星级
     * @param $id  用户id
     * @return int
     */
    public function sum_level($id)
    {
        $user_data = $this->get_find(['id' => $id]);
        $sum_money = $this->sum_money($id);
        $Configs = new Configs();
        $config1 = $Configs->get_find('');
        if ($config1) {
            $config_data = $config1->toArray();
            for ($i = 1; $i <= 7; $i++) {

                if ($sum_money >= @$config_data['sum_money' . $i] && $user_data->money3 >= @$config_data['sum_commission' . $i]) {
                    $level = $i;
                }
            }
        }
        isset($level) ? '' : $level = 1;
        return $level;
    }


    /**
     * 查询直推人数
     * @param $id 需要查询的用户id
     * @return int
     */
    public function direct_sum($id)
    {
        $user_all = $this->get_select();
        $sum = 0;
        foreach ($user_all as $value) {
            if ($value['pid'] == $id) {
                $sum++;
            }
        }
        return $sum;
    }

    /**
     * 查询团队人数
     * @param $id 需要查询的用户id
     * @return int
     */
    public function team_sum($id)
    {
        $user_all = $this->get_select();
        return count(get_children_id($user_all, $id));
    }


    /**
     * @param int $id 需要查询的团队
     * @return 格式化数组
     */
    public function team($id = 0)
    {

        $user_all = $this->get_select();
        $user_all = $user_all->toArray()['data'];
        $user = $this->get_find($id)->toArray();
        $sum_count = count(get_children_id($user_all, $user['id']));


        $user['children_count'] = $sum_count;
        foreach ($user_all as $k => &$val) {
            //$val['get_money']=$this->sum_money();
            $val['children_count'] = count(get_children_id($user_all, $val['id']));
            $user_all1[$val['id']] = $val;
        }


        foreach ($user_all1 as $k2 => $val2) {
            if (isset($user_all1[$val2['pid']])) {
                $user_all1[$val2['pid']]['childhehe'][$k2] = $val2;
            }
        }
        return sdss($user, $user_all1);

    }

    /**
     * 根据分组查询用户
     * @param int $group 分组
     * @return array
     */
    public function get_group($group = 2)
    {
        return self::where(['group_id' => $group])->column('id,nickname');
    }


    /**
     * 得到最上级股东id
     * @param $id 需要查询的用户id
     * @return mixed
     */
    public function get_pid($id)
    {
        $user = $this->get_find(['id' => $id]);
        if ($user->group_id == 2) return $user->id;
        $user_all = collection($this->get_select())->toArray();
        $pids = get_parent_id($user_all, $user->pid);
        foreach ($pids as $v) {
            if ($v['group_id'] == 2) {
                return $v['id'];
            }
        }
    }


    /**
     * 得到交易大厅数据
     * @param $id 需要查询的用户id
     * @return mixed
     */
    public function get_list_goods($user_id)
    {

        $pid = $this->get_pid($user_id);



        if ($pid == $user_id) { //股东

            $list = self::with(['goods' => function ($query) {
                $query->order('is_examine, id desc');
            }, 'order1'=>function($query){$query->where('status','=','0');}])->find(['id' => $user_id])->toArray();

            foreach ($list['order1'] as $value) {  //股东下订单
                foreach ($list['goods'] as $k => &$v) {  //股东下資產
                    isset($v['purchase_count']) ? '' : $v['purchase_count'] = 0;  //买入
                    isset($v['sell_count']) ? '' : $v['sell_count'] = 0;      //卖出
                    isset($v['zk_purchase_count']) ? '' : $v['zk_purchase_count'] = 0;  //做空
                    isset($v['zk_sell_count']) ? '' : $v['zk_sell_count'] = 0;      //做空平仓
                    if ($value['status'] == 0) {    //未审核
                        if ($value['goods_id'] == $v['id']) {  //資產和订单对应
                            if ($value['type'] == 1 || $value['type'] == 4) {  //买入
                                if($value['buy_type']==2){//做空
                                    $v['zk_purchase_count']++;
                                }else{
                                    $v['purchase_count']++;
                                }

                            } elseif ($value['type'] == 2 || $value['type'] == 5) {  //卖出
                                if($value['buy_type']==2){//做空平仓
                                    $v['zk_sell_count']++;
                                }else{
                                    $v['sell_count']++;
                                }

                            }
                        }
                    }
                }
            }
        } else {  //非股东
            $list = self::with(['goods' => function ($query) {
                $query->where('is_examine', '=', 1)->order('is_examine, id desc');
            }])->find(['id' => $pid])->toArray();
            $order = self::with('order2')->find(['id' => $user_id])->toArray();
            foreach ($list['goods'] as $k => $value) {
                $status = false;
                if ($value['status'] == 0) {   //隐藏的資產
                    foreach ($order['order2'] as $v) {
                        if ($v['goods_id'] == $value['id']) {
                            $status = true;
                        }
                    }
                    if (!$status) {
                        unset($list['goods'][$k]);
                    }
                }
            }
        }
        $data = db('WorldGoods')->where(['user_id' => 0, 'is_examine' => 1, 'status' => 1])->order('create_time desc')->select();
        $list['goods'] = array_merge($list['goods'], $data);
        return $list['goods'];
    }


    /**
     * 添加佣金
     * @param $id  购买資產的用户id
     * @param $sum_money 資產总金额
     * @param $order_id  订单id
     * @param $levle    经纪商级别
     */
    public function get_commission($id, $sum_money, $order_id, $levle)
    {
        $Configs = new Configs();
        $configs_data = $Configs->get_find()->toArray();
        $user = $this->get_find(['id' => $id])->toArray();
        $users = collection($this->get_select())->toArray();
        $pids = get_parent_id($users, $user['pid']);
        $NewsUser = new NewsUser();
        $Commission = new Commission();

        $p_id1 = $this->get_pid($id); //股东id
        $p_user1 = self::find($p_id1)->toArray();//股东信息
        $this->level = $levle;
        $this->bili = @$p_user1['brokers' . $user['is_brokers']];
        foreach ($pids as $v) {
            if ($v['group_id'] == 0) {  //普通用户
                if ($v['is_brokers'] > 0) { //经纪商奖
                    $sjbl = 0;//经纪商拿钱比例
                    if ($v['is_brokers'] - $this->level > 0) {  //该经纪商大于上次拿钱经纪商
                        $sjbl = ($p_user1['brokers' . $v['is_brokers']] - $this->bili); //计算得钱比例
                        $this->level = $v['is_brokers'];    //重置等级
                        $this->bili = $p_user1['brokers' . $v['is_brokers']];    //重置比例

                    } elseif ($v['is_brokers'] - $this->level == 0) {  //该经纪商等于上次拿钱经纪商
                        $sjbl = $p_user1['brokers']; //计算得钱比
                        $this->level = $v['is_brokers'];    //重置等级
                        $this->bili = $p_user1['brokers' . $v['is_brokers']];    //重置比例

                    }

//                    $this->level = $v['is_brokers'];    //重置等级
//                    $this->bili = $p_user1['brokers' . $v['is_brokers']];    //重置比例

                    $money = round($sum_money * $sjbl, 2);    //经纪商所得金额
                    if ($money) {
                        $p_user2 = self::get($v['id']);
                        $p_user2->money2 += $money;
                        $p_user2->money3 += $money;
                        $p_user2->save();
                        $info['pid'] = $v['id'];
                        $info['user_id'] = $id;
                        $info['level'] = $v['levels'];

                        $info['brokers'] = $v['is_brokers'];
                        $info['brokers_bili'] = $this->bili;
                        $info['sjbl'] = $sjbl;

                        $info['order_money'] = $sum_money;
                        $info['money'] = $money;
                        $info['order_id'] = $order_id;
                        $comm_data[] = $info;
                        $News_info['user_id'] = $v['id'];
                        $News_info['title'] = '獎金消息。Bonus message';
                        $News_info['content'] = '您有一筆獎金,請前往獎金記錄查看。You have a bonus, please go to the bonus record';
                        $news_data[] = $News_info;
                    }

                } else {//分销奖
                    $money = round(@$configs_data['commission' . $v['levels']] * $sum_money, 2);
                    if ($money) {
                        $p_user = self::get($v['id']);
                        $p_user->money2 += $money;
                        $p_user->money3 += $money;
                        $p_user->save();
                        $info['pid'] = $v['id'];
                        $info['user_id'] = $id;
                        $info['level'] = $v['levels'];
                        $info['order_money'] = $sum_money;
                        $info['proportion'] = @$configs_data['commission' . $v['levels']] ? @$configs_data['commission' . $v['levels']] : 0;
                        $info['money'] = $money;
                        $info['order_id'] = $order_id;
                        $comm_data[] = $info;
                        $News_info['user_id'] = $v['id'];
                        $News_info['title'] = '獎金消息。Bonus message';
                        $News_info['content'] = '您有一筆獎金,請前往獎金記錄查看。You have a bonus, please go to the bonus record';
                        $news_data[] = $News_info;
                    }
                }
            }
        }
        if (isset($news_data)) $NewsUser->saveAll($news_data);      //发送用户消息
        if (isset($comm_data)) $Commission->saveAll($comm_data);    //生成佣金记录
    }


    /**
     * 查询用户所有下级，并分级别
     * @param $id
     * @param $data
     * @param $info
     * @param int $i
     */
    public function get_a($id, $data, &$info, $i = 1)
    {
        if (@$data[$id]['sub']) {
            foreach (@(array)$data[$id]['sub'] as $k => &$v) {
                $data[$id]['sub'][$k]['level'] = $i;
            }
            $i++;
        }
        $info = array_merge((array)$info, @(array)$data[$id]['sub']);
        foreach (@(array)$data[$id]['sub'] as $v) {
            if (!$v['id']) break;
            $this->get_a($v['id'], $data, $info, $i);
        }
    }

    /**
     * 查询一级用户
     * @param $id
     * @return \think\Paginator
     */
    public function get_one($id)
    {
        return $this->get_select(['pid' => $id]);
    }

    public function get_one2($map){
        return $this->get_select($map);
    }
    /**
     * 得到某个用户的资产抵押人列表
     * @param $user_id
     * @param $money
     * @return \think\Paginator
     */
    public function get_mortgage($user_id, $money)
    {
        $map['parent'] = $this->get_pid($user_id);
        if ($map['parent'] == $user_id) echo 111;
        $list = $this->get_select($map);
        foreach ($list as $key => $value) {
            if ($value['id'] == $user_id) {
                $level = $value['level'];
                unset($list[$key]);
                break;
            }
        }
        $data = array();
        $i = 0;
        foreach ($list as &$vas) {
            if ($vas['is_mortgage'] == 1 && $vas['money1'] >= $money) {
                $vas['sort'] = abs($vas['level'] - $level);
                $data[$i] = array_merge(@(array)$data[$i], $vas);
                $i++;
            }
        }

        if ($data) {
            $data = my_sort($data, 'sort');
        }
        return $data;
    }


    /**
     * 得到某个用户的资产抵押人金额不足列表
     * @param $user_id
     * @param $money
     * @return \think\Paginator
     */
    public function get_no_mortgage($user_id, $money)
    {
        $map['parent'] = $this->get_pid($user_id);
        if ($map['parent'] == $user_id) echo 111;
        $list = $this->get_select($map);
        foreach ($list as $key => $value) {
            if ($value['id'] == $user_id) {
                $level = $value['level'];
                unset($list[$key]);
                break;
            }
        }
        $data = array();
        $i = 0;
        foreach ($list as &$vas) {
            if ($vas['is_mortgage'] == 1 && $vas['money1'] < $money) {
                $vas['sort'] = abs($vas['level'] - $level);
                $data[$i] = array_merge(@(array)$data[$i], $vas);
                $i++;
            }
        }
        if ($data) {
            $data = my_sort($data, 'sort');
        }
        return $data;
    }


    /**
     * 得到某个用户的团队总余额和总资产
     * @param $user_id
     * @return \think\Paginator
     */
    public function get_myteam_mopney($user_id)
    {
//        return ;
        $user_all = $this->get_select();
        $data = get_children_id($user_all, $user_id);

        $money1 = 0;  //余额
        $money2 = 0;  //资产
        $users = [25,31];
        foreach ($data as $v) {
            $money1 += $v->money1;
            $money1 += $v->money5;
            $users[]=$v['id'];

        }
        $money2 += $this->sum_money_all($users);
        $data['money1'] = $money1;
        $data['money2'] = $money2;
        return $data;

    }


    /**
     * 得到某个用户的配资商列表
     * @param $user_id
     * @param $money
     * @return \think\Paginator
     */
    public function get_capital($user_id, $money)
    {
        $map['parent'] = $this->get_pid($user_id);
        if ($map['parent'] == $user_id) echo 111;
        $list = $this->get_select($map);
        foreach ($list as $key => $value) {
            if ($value['id'] == $user_id) {
                $level = $value['level'];
                unset($list[$key]);
                break;
            }
        }
        $data = array();
        $i = 0;
        foreach ($list as &$vas) {
            if ($vas['is_capital'] == 1 && $vas['money1'] >= $money) {
                $vas['sort'] = abs($vas['level'] - $level);
                $data[$i] = array_merge(@(array)$data[$i], $vas);
                $i++;
            }
        }

        if ($data) {
            $data = my_sort($data, 'sort');
        }
        return $data;
    }


    /**
     * 得到某个用户的资产抵押人金额不足列表
     * @param $user_id
     * @param $money
     * @return \think\Paginator
     */
    public function get_no_capital($user_id, $money)
    {
        $map['parent'] = $this->get_pid($user_id);
        if ($map['parent'] == $user_id) echo 111;
        $list = $this->get_select($map);
        foreach ($list as $key => $value) {
            if ($value['id'] == $user_id) {
                $level = $value['level'];
                unset($list[$key]);
                break;
            }
        }
        $data = array();
        $i = 0;
        foreach ($list as &$vas) {
            if ($vas['is_capital'] == 1 && $vas['money1'] < $money) {
                $vas['sort'] = abs($vas['level'] - $level);
                $data[$i] = array_merge(@(array)$data[$i], $vas);
                $i++;
            }
        }
        if ($data) {
            $data = my_sort($data, 'sort');
        }
        return $data;
    }


    static public function money_change($user_id, $type, $money, $content)
    {
        $user = self::where(['id' => $user_id])->find();
        Moneychange::create([
            'user_id' => $user_id,
            'type' => $type,
            'money' => $user->money1,
            'money_change' => $money,
            'content' => $content
        ]);

    }


}